<template>
  <div>
    <!-- 底部弹出CtaForm -->
    <van-popup v-if="loading" v-model:show="localCtaShow" position="bottom">
      <!--  图片    -->
      <div class="w-full p-2">
        <van-image
            width="100%"
            height="25vw"
            :src="dataInfo.form?.thumb"
            fit="cover">
          <template #error>
            <div class="bg-gray-400" style="height: 50vw;width: 100vw"></div>
          </template>
        </van-image>
      </div>

      <!--   表单   -->
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <template v-for="(item) in dataInfo.form?.question" :key="item.code">
            <van-field v-if="item.code !== 'sex'"
                       v-model="formParam.data[item.code]"
                       :name="item.code"
                       :label="item.label"
                       :placeholder="`请输入您的`+item.label"
                       clearable
                       :required="true"
                       :rules="rules[item.code]">
            </van-field>
            <van-field v-else
                       :label="item.label"
                       :required="true"
                       :rules="rules[item.code]">
              <template #input>
                <van-radio-group direction="horizontal" v-model="formParam.data[item.code]">
                  <van-radio :name="1">男</van-radio>
                  <van-radio :name="2">女</van-radio>
                </van-radio-group>
              </template>
            </van-field>

            <van-field v-if="item.code === 'mobile'"
                       name="mobile_code"
                       v-model="formParam.data.mobile_code"
                       label="验证码"
                       placeholder="请输入验证码"
                       clearable
                       type="number"
                       :required="true"
                       :rules="rules.mobile_code"
            >
              <!-- 自定义右侧按钮 -->
              <template #button>
                <van-button
                    type="primary"
                    size="small"
                    @click="dealSendCode"
                    :disabled="countMobileDown > 0 || !isMobileValid"
                >
                  {{ countMobileDown > 0 ? countMobileDown + 's后重发' : '发送验证码' }}
                </van-button>
              </template>
            </van-field>
            <van-field v-if="item.code === 'email'"
                       name="mobile_code"
                       v-model="formParam.data.email_code"
                       label="验证码"
                       placeholder="请输入验证码"
                       clearable
                       type="number"
                       :required="true"
                       :rules="rules.email_code"
            >
              <!-- 自定义右侧按钮 -->
              <template #button>
                <van-button
                    type="primary"
                    size="small"
                    @click="dealSendEmailCode"
                    :disabled="countEmailDown > 0 || !isEmailValid"
                >
                  {{ countEmailDown > 0 ? countEmailDown + 's后重发' : '发送验证码' }}
                </van-button>
              </template>
            </van-field>
          </template>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button block type="primary" native-type="submit">提交</van-button>
        </div>
      </van-form>

    </van-popup>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive,computed,onUnmounted} from 'vue';
import { ctaInfo, ctaInfoType, ctaFormSubmit } from "@/api/cta";
import { sendCode } from "@/api/sms";
import { ctaSendEmailCode } from "@/api/mail";
import {useRoute} from "vue-router";
import {showSuccessToast} from "vant";

const props = defineProps({
  omniUserUuid: {
    type: String,
    required: true
  },
  ctaUuid: {
    type: String,
    required: true
  },
  sceneType: {
    type: String,
    required: true
  },
  sceneUuid: {
    type: String,
    required: true
  },
  ctaShow: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["updateCtaShow", "updateCtaStatus"]);

const localCtaShow = computed({
  get() {
    return props.ctaShow;
  },
  set(value) {
    emit('updateCtaShow', value);
  }
});



const dataInfo = reactive<ctaInfoType>({
  uuid:"",
  mid:0,
  name:"",
  type:"",
  work_qrcode:{
    guide: "",
    reply: "",
    member:""
  },
  wechat_qrcode:{
    guide: "",
    reply: ""
  },
  form: {
    thumb:"",
    material_uuid:"",
    question:[]
  },
  qrcode_url:""
});


onMounted(() => {
  console.log("加载form")
  getCtaInfo()
});



const loading = ref(false)
const getCtaInfo = async () => {
  try {
    const response = await ctaInfo(props.ctaUuid,props.sceneType,props.sceneUuid);
    if (response.data) {
      Object.assign(dataInfo,response.data)
    }
    loading.value = true
  } catch (e) {
    console.error(e);
  }
}


onUnmounted(() => {
  console.log("销毁CtaWechat")
});


const route = useRoute();
const aggListUuid = route.params.aggListUuid as string;


const formParam = ref({
  omni_user_uuid:props.omniUserUuid,
  agg_uuid:aggListUuid,
  cta_uuid:props.ctaUuid,
  entity_type:props.sceneType,
  entity_uuid:props.sceneUuid,
  data:{
    name: '',
    mobile: '',
    mobile_code: '',
    email:'',
    email_code:'',
    company:'',
    position:'',
    address:'',
    sex:''
  }
});

const onSubmit = () => {
  loading.value = true;
  try {
    ctaFormSubmit(formParam.value).then((response) => {
      if(response.data?.uuid !== undefined){
        emit("updateCtaStatus", true, true);
      }
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
};

const validateStringLength = (value: string,min:number=2,max:number=4): boolean => value.length >= min && value.length <= max;

const rules = {
  name: [
    {required: true, message: '请填写姓名'},
    {validator: (value: string) => validateStringLength(value, 2, 10), message: '长度必须在2到10个字符之间'}
  ],
  mobile:[
    { required: true, message: '请填写手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }
  ],
  mobile_code:[
    { required: true, message: '请填写手机验证码!' },
    { pattern: /^\d{6}$/, message: '手机验证码必须是6位数字'}
  ],
  email: [
    { required: true, message: '请填写电子邮件地址' },
    { pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, message: '请输入有效的电子邮件地址' }
  ],
  email_code:[
    { required: true, message: '请填写手机验证码' },
    { pattern: /^\d{6}$/, message: '手机验证码必须是6位数字'}
  ],
  company:[
    {required: true, message: '请填写公司(单位)'},
    {validator: (value: string) => validateStringLength(value, 2, 20), message: '长度必须在2到20个字符之间'}
  ],
  position:[
    {required: true, message: '请填写职务'},
    {validator: (value: string) => validateStringLength(value, 2, 10), message: '长度必须在2到10个字符之间'}
  ],
  address:[
    {required: true, message: '请填写地址'},
    {validator: (value: string) => validateStringLength(value, 2, 20), message: '长度必须在2到20个字符之间'}
  ],
  sex:[
    { required: true, message: '请选择一个选项' },
  ],
};



const countMobileDown = ref(0);
const dealSendCode = () => {
  // 模拟发送验证码的逻辑
  console.log('发送验证码到手机号：', formParam.value.data.mobile);
  ctaSendCode()
  // 开始倒计时
  countMobileDown.value = 60;
  const timer = setInterval(() => {
    if (countMobileDown.value > 0) {
      countMobileDown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};

const isMobileValid = computed(() => {
  return formParam.value.data.mobile && formParam.value.data.mobile.match(/^1[3-9]\d{9}$/);
});


const countEmailDown = ref(0);
const dealSendEmailCode = () => {
  // 模拟发送验证码的逻辑
  console.log('发送验证码到手机号：', formParam.value.data.email);
  sendEmailCode()
  // 开始倒计时
  countEmailDown.value = 60;
  const timer = setInterval(() => {
    if (countEmailDown.value > 0) {
      countEmailDown.value--;
    } else {
      clearInterval(timer);
    }
  }, 1000);
};
const isEmailValid = computed(() => {
  return formParam.value.data.email && formParam.value.data.email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/);
});

const ctaSendCode = () => {
  loading.value = true;
  try {
    sendCode({
      mobile:formParam.value.data.mobile
    }).then((response) => {
      if(response.data.status){
        showSuccessToast('发送成功');
      }
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
};
const sendEmailCode = () => {
  loading.value = true;
  try {
    ctaSendEmailCode({
      email:formParam.value.data.email
    }).then((response) => {
      if(response.data.status){
        showSuccessToast('发送成功');
      }
    })
  } catch (e) {
    console.log(e);
  } finally {

  }
};



</script>

<style scoped>
</style>
